<!--
;; MIT License

;; Copyright (c) 2025 三体自动化技术协会

;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:

;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.

;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
-->
<!-- 本例程用来演示表格矩形区域内容选择
    其中技术需要原模原样复刻到<table id="FRAME-BUFFER">...</table>上面。
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表格矩形选择</title>
    <style>
        .table-container {
            overflow: auto;
            border: 1px solid #ddd;
            position: relative;
        }
        
        
        td {
            border: 1px solid #ddd;
            padding: 2px;
            text-align: center;
            font-size: 10px;
            height: 12px;
            user-select: none;
        }
        
        .selected {
            background-color: #4dabf7;
            color: white;
        }
        
        .selection-box {
            position: absolute;
            background-color: rgba(77, 171, 247, 0.3);
            border: 2px solid #4dabf7;
            pointer-events: none;
            z-index: 10;
            display: none;
        }
    </style>
</head>
<body>
    <div class="table-container" id="tableContainer">
        <table id="dataTable"></table>
        <div class="selection-box" id="selectionBox"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const table = document.getElementById('dataTable');
            const tableContainer = document.getElementById('tableContainer');
            const selectionBox = document.getElementById('selectionBox');
            
            const rows = 64;
            const cols = 64;
            let isSelecting = false;
            let startCell = null;
            let selectedCells = [];
            let selectionBounds = null;
            
            // 创建表格
            function createTable() {
                for (let i = 0; i < rows; i++) {
                    const row = document.createElement('tr');
                    for (let j = 0; j < cols; j++) {
                        const cell = document.createElement('td');
                        cell.textContent = `${i+1},${j+1}`;
                        cell.dataset.row = i;
                        cell.dataset.col = j;
                        row.appendChild(cell);
                    }
                    table.appendChild(row);
                }
            }
            
            // 获取单元格的行列索引
            function getCellIndex(cell) {
                return {
                    row: parseInt(cell.dataset.row),
                    col: parseInt(cell.dataset.col)
                };
            }
            
            // 获取鼠标所在的单元格
            function getCellFromPoint(x, y) {
                const elements = document.elementsFromPoint(x, y);
                for (const el of elements) {
                    if (el.tagName === 'TD') {
                        return el;
                    }
                }
                return null;
            }
            
            // 清除所有选择
            function clearSelection() {
                selectedCells.forEach(cell => {
                    cell.classList.remove('selected');
                });
                selectedCells = [];
                selectionBounds = null;
            }
            
            // 选择矩形区域
            function selectRect(startRow, startCol, endRow, endCol) {
                clearSelection();
                
                const minRow = Math.min(startRow, endRow);
                const maxRow = Math.max(startRow, endRow);
                const minCol = Math.min(startCol, endCol);
                const maxCol = Math.max(startCol, endCol);
                
                selectionBounds = { minRow, maxRow, minCol, maxCol };
                
                for (let i = minRow; i <= maxRow; i++) {
                    for (let j = minCol; j <= maxCol; j++) {
                        const cell = table.rows[i].cells[j];
                        cell.classList.add('selected');
                        selectedCells.push(cell);
                    }
                }
            }
            
            // 复制选中内容到剪贴板
            function copySelectionToClipboard() {
                if (!selectionBounds || selectedCells.length === 0) return;
                
                const { minRow, maxRow, minCol, maxCol } = selectionBounds;
                
                // 构建文本内容 - 只使用换行符
                let textContent = '';
                for (let i = minRow; i <= maxRow; i++) {
                    let rowContent = '';
                    for (let j = minCol; j <= maxCol; j++) {
                        const cell = table.rows[i].cells[j];
                        rowContent += cell.textContent;
                    }
                    textContent += rowContent;
                    if (i < maxRow) textContent += '\n';
                }
                
                // 使用Clipboard API复制到剪贴板
                navigator.clipboard.writeText(textContent)
                    .catch(err => {
                        // 降级方案
                        const textArea = document.createElement('textarea');
                        textArea.value = textContent;
                        document.body.appendChild(textArea);
                        textArea.select();
                        document.execCommand('copy');
                        document.body.removeChild(textArea);
                    });
            }
            
            // 鼠标按下事件
            tableContainer.addEventListener('mousedown', function(e) {
                if (e.button !== 0) return;
                
                const cell = getCellFromPoint(e.clientX, e.clientY);
                if (!cell) return;
                
                isSelecting = true;
                startCell = cell;
                
                const rect = tableContainer.getBoundingClientRect();
                selectionBox.style.left = (e.clientX - rect.left) + 'px';
                selectionBox.style.top = (e.clientY - rect.top) + 'px';
                selectionBox.style.width = '0';
                selectionBox.style.height = '0';
                selectionBox.style.display = 'block';
                
                e.preventDefault();
            });
            
            // 鼠标移动事件
            tableContainer.addEventListener('mousemove', function(e) {
                if (!isSelecting) return;
                
                const rect = tableContainer.getBoundingClientRect();
                const currentX = e.clientX - rect.left;
                const currentY = e.clientY - rect.top;
                
                const startX = parseFloat(selectionBox.style.left);
                const startY = parseFloat(selectionBox.style.top);
                
                selectionBox.style.width = Math.abs(currentX - startX) + 'px';
                selectionBox.style.height = Math.abs(currentY - startY) + 'px';
                
                if (currentX < startX) {
                    selectionBox.style.left = currentX + 'px';
                }
                
                if (currentY < startY) {
                    selectionBox.style.top = currentY + 'px';
                }
                
                const endCell = getCellFromPoint(e.clientX, e.clientY);
                if (endCell) {
                    const startIdx = getCellIndex(startCell);
                    const endIdx = getCellIndex(endCell);
                    selectRect(startIdx.row, startIdx.col, endIdx.row, endIdx.col);
                }
            });
            
            // 鼠标释放事件
            document.addEventListener('mouseup', function() {
                if (!isSelecting) return;
                isSelecting = false;
                selectionBox.style.display = 'none';
            });
            
            // 键盘事件处理
            document.addEventListener('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
                    if (selectedCells.length > 0) {
                        copySelectionToClipboard();
                        e.preventDefault();
                    }
                }
            });
            
            // 初始化表格
            createTable();
        });
    </script>
</body>
</html>